<template>
  <div class="app-container">
    <!-- <mainTilte title="组合商品管理" /> -->
    <form-selections :is-active="false" :items="formItems" :query-param.sync="searchParams" display="block" @handleSearch="handleSearch" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'productCombination@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="add">
          新增组合</el-button>
        <!-- <el-button type="danger">批量删除</el-button> -->
        <el-button v-action="'productCombination@disable'" size="small" type="danger" @click="stopClick">禁用</el-button>
        <el-button v-action="'productCombination@enable'" size="small" type="primary" @click="startClick">启用</el-button>
        <el-button v-action="'productCombination@productCombination'" size="small" type="primary" @click="productImport">导入组合商品</el-button>
        <el-button v-action="'productCombination@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出组合商品</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </div>
    <div v-loading="loading" class="page-grid">
      <egrid :screen-heigh="screenHeigh" class="egrid" stripe fit border highlight-current-row element-loading-text="正在努力加载中..." :column-type="['selection']" :data="tableData" :columns="columns" :columns-schema="columnsSchema" :columns-handler="columnsHandler" @selection-change="checkIds" />
      <epagination v-if="tableData" :total="total" :current="searchParams.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
    </div>
    <!-- 导入 -->
    <import-dialog url="/productCombination/productCombination" title="导入组合商品" :form-visible.sync="importDialogVisible" @download="downLoad" @handleRefresh="handleRefresh" />
    <!-- 导出 -->
    <down-modul :form-visible-down.sync="formVisibleDown" url="/productCombinations/export" :search-param="searchParams" :options-modul="downOptions" />
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import thund from '@/components/base/thund'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import dicValues from '@/components/dicTransform/index'
import codeItem from '@/components/base/code'
import {
  action
} from '@/directive/permission/index.js' // 权限判断指令
import cacheList from '@/layout/mixin/cacheList'
import {
  downloadStream
} from '@/utils/index'
import importDialog from '@/components/importDialog/index'
import DownModul from '@/components/DownModul/index'
export default {
  name: 'PortfolioManager',
  directives: {
    action
  },
  components: {
    importDialog,
    DownModul
  },
  mixins: [list, cacheList],
  data() {
    const DICTIONARIES = {
      auditStatus: [
        // 1：正常，2：禁用
        {
          code: 1,
          name: '启用'
        },
        {
          code: 2,
          name: '禁用'
        }
      ]
    }
    return {
      otherHeight: 355,
      downOptions: [
        {
          key: 'code',
          label: '商品组合编码'
        },
        {
          key: 'name_ch',
          label: '商品组合中文名称'
        },
        {
          key: 'shop_name',
          label: '商品组合所属店铺'
        },
        {
          key: 'goods_code',
          label: '商品SKU'
        },
        {
          key: 'goods_name_ch',
          label: '商品中文名称'
        },
        {
          key: 'packing_method_text',
          label: '商品包装方式'
        },
        {
          key: 'category_names',
          label: '商品分类'
        },
        {
          key: 'price',
          label: '基准价格'
        },
        {
          key: 'number',
          label: '商品数量'
        },
        {
          key: 'created_at',
          label: '创建时间'
        }
      ],
      formVisibleDown: false,
      exportLoading: false,
      importDialogVisible: false,
      componentName: 'PortfolioManager',
      allAmount: '',
      value: '',
      value1: [],
      loading: false,
      dialogAddVisible: false, // 新增供应商弹框
      title: '',
      loadingText: '',
      rule: {},
      formItems: [{
        label: '名称/编码',
        key: 'keys',
        type: 'input',
        placeholder: '请输入名称/编码'
      },
      {
        label: '所属店铺',
        key: 'shop_id',
        type: 'select',
        placeholder: '请选择店铺',
        filterable: true,
        options: []
      }
      ],
      /** *
         * 定义搜索框
         */
      searchParams: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        keys: '',
        shop_id: ''
      },
      tableData: [{
        code: '111'
      }],
      /** *
         * 定义显示的表格
         */
      columns: [{
        label: '组合编码',
        prop: 'code',
        align: 'center',
        width: '240',
        tooltip: false
      },
      {
        label: '中文名称',
        prop: 'name_ch',
        id: 'id',
        width: '180',
        align: 'center',
        tooltip: false
      },
      {
        label: '英文名称',
        prop: 'name_en',
        align: 'center',
        tooltip: false
      },
      {
        label: '套餐单价',
        prop: 'price_usd',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '所属店铺',
        prop: 'shop_name',
        width: '100',
        align: 'center',
        tooltip: true
      },
      {
        label: '状态',
        prop: 'is_disable',
        width: '100',
        align: 'center',
        tooltip: false
      },
      {
        label: '创建人',
        prop: 'creator_name',
        width: '112',
        align: 'center',
        tooltip: false
      },
      {
        label: '创建时间',
        prop: 'created_at',
        align: 'center',
        tooltip: false,
        width: '174'
      },
      {
        label: '修改人',
        prop: 'update_name',
        width: '112',
        align: 'center',
        tooltip: false
      },
      {
        label: '修改时间',
        prop: 'updated_at',
        align: 'center',
        width: '174',
        tooltip: false
      }
      ],
      /** *
         * 字典表组件
         */
      columnsSchema: {
        缩略图: {
          propsHandler({
            col,
            row
          }) {
            return {
              img: row.image_url
            }
          },
          component: thund
        },
        中文名称: {
          propsHandler({
            col,
            row
          }) {
            return {
              code: row[col.prop],
              id: row[col.id]
            }
          },
          listeners: {
            click: this.toInfo
          },
          component: codeItem
        },
        状态: {
          propsHandler({
            col,
            row
          }) {
            return {
              dictionaries: DICTIONARIES['auditStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      issignContract: [{
        name: '发票号',
        code: 'invoice_no'
      },
      {
        name: '付款单位',
        code: 'payer'
      },
      {
        name: '采购单号',
        code: 'purchase_code'
      }
      ],
      form: {
        id: null,
        supplierCode: null, // 供应商代码
        supplierName: null, // 供应商名称
        settlementCycle: null, // 结算周期
        buyer: null, // 采购员
        contacts: '', // 联系人
        phone: null, // 联系人手机
        fixedTelephone: null, // 固定电话
        fax: null, // 传真
        // address: null, // 地址
        postcode: null, // 邮编
        payment: null, // 预付款比例
        notes: null // 备注说明
      },
      cachePaths: [
        '/product/portfolioManage/addPortfolio',
        '/portfolioManage/portfolioInfo'
      ]
    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.query()
    this.getShop()
  },
  activated() {
    this.query()
    this.getShop()
  },
  methods: {
    // 导出
    handleExport() {
      const vm = this
      vm.formVisibleDown = true
      //   vm.exportLoading = true
      //   const url = '/productPlatformSkus/export'
      //   const { code } = vm.searchParams
      //   const params = {
      //     code
      //   }
      //   vm.$http.post(url, params).then(res => {
      //     downloadxlsx(res.data)
      //     vm.exportLoading = false
      //   }).catch(() => {
      //     vm.exportLoading = false
      //   })
    },
    // 获取店铺
    getShop() {
      const vm = this
      const params = { limit: 100000, page: 1 }
      vm.$http.get(`/shop`, { params: params }).then(res => {
        const data = res.data.map((arr) => {
          return {
            value: arr.id,
            label: arr.shop_name
          }
        })
        vm.formItems = vm.formItems.map(arr => {
          if (arr.key === 'shop_id') {
            arr.options = data
          }
          return arr
        })
      })
    },
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/productCombination/templateCombination', {
          responseType: 'blob'
        })
        .then((res) => {
          downloadStream(res, '组合商品导入模板.xlsx')
        })
    },
    // 导入
    productImport() {
      const vm = this
      vm.importDialogVisible = true
    },
    // 去详情
    toInfo(id) {
      const vm = this
      // const item = vm.tableData.find((e) => e.id === id)
      vm.$router.push({
        path: `/portfolioManage/portfolioInfo/${id}`
      })
    },
    handleSearch() {
      const vm = this
      vm.searchParams.page = 1
      vm.query()
    },
    handleRefresh() {
      const vm = this
      vm.searchParams.page = 1
      vm.searchParams.limit = 10
      vm.searchParams.keys = ''
      vm.searchParams.shop_id = ''
      vm.query()
    },
    handleSizeChange(val) {
      this.searchParams.limit = val
      this.query()
    },
    handleCurrentChange(val) {
      this.searchParams.page = val
      this.query()
    },
    add() {
      this.$router.push('/product/portfolioManage/addPortfolio')
    },
    query() {
      this.initTableData(
        `/productCombination?page=${this.searchParams.page}&limit=${this.searchParams.limit}&keys=${this.searchParams.keys}&shop_id=${this.searchParams.shop_id}`
      )
    },
    // 新增-保存
    saveData() { },
    stopClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }
      vm.$confirm(`确定批量禁用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/productCombination/disable`, {
            ids: vm.ids
          })
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('禁用成功')
              vm.query()
            }
          })
      })
    },
    startClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }

      vm.$confirm(`确定批量启用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/productCombination/enable`, {
            ids: vm.ids
          })
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('启用成功')
              vm.query()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({
          row
        }) {
          const show = row.is_disable === 2
          return {
            row,
            del: show,
            edit: show,
            delAction: 'productCombination@delete',
            editAction: 'productCombination@update'
          }
        },
        component: operationBtnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          editTableClick(row) {
            that.$router.push({
              path: '/product/portfolioManage/addPortfolio',
              query: {
                title: '编辑组合商品',
                id: row.id
              }
            })
          },
          deleteTableClick(row) {
            that
              .$confirm('确认要删除？', '提示', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.$http
                  .delete(`/productCombination/${row.id}`)
                  .then((res) => {
                    if (res.code === 10000) {
                      that.$message.success('删除成功')
                      that.query()
                    }
                  })
                  .catch((err) => {
                    console.log(err)
                  })
              })
              .catch((action) => { })
          }
        }
      })
    }
  }
}

</script>

<style lang="scss" scoped>
.minheight-400 {
  height: 400px;
  overflow-y: auto;
}
</style>
